package com.yangye.pidoublename.service.impl;

import com.yangye.pidoublename.service.DoubleNameService;
import com.yangye.pidoublename.service.ProvinceEnum;
import com.yangye.pidoublename.vo.DoubleNameVo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author yangye
 * @date 2019/9/20
 */
@Service
public class BeiJingServiceImpl implements DoubleNameService {

	@Autowired
	@Qualifier("sslRestTemplate")
	private RestTemplate sslRestTemplate;

	private final String QUERY_URL = "https://gaj.beijing.gov.cn/rkgl/reserve/checkNameSexNum";

	@Override
	public DoubleNameVo findByName(String name) {
		MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
		params.add("checkName", name);
		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(params, httpHeaders);
		String response = sslRestTemplate.postForObject(QUERY_URL, request, String.class);
		Document doc = Jsoup.parse(response);
		String text = doc.select(".alert-danger strong").first().text();
		/**
		 * text：北京市户籍人口杨野的 男性人数为21人. 北京市户籍人口杨野的 女性人数为2人.
		 * 提取人数
		 */
		String regex = "\\D+(\\d+)人\\D+(\\d+)人";
		Pattern p = Pattern.compile(regex);
		Matcher matcher = p.matcher(text);
		matcher.find();
		int man = Integer.parseInt(matcher.group(1));
		int woman = Integer.parseInt(matcher.group(2));

		DoubleNameVo doubleNameVo = new DoubleNameVo();
		doubleNameVo.setProvince(ProvinceEnum.BEIJING.getName());
		doubleNameVo.setName(name);
		doubleNameVo.setMan(man);
		doubleNameVo.setWoman(woman);
		doubleNameVo.setTotal(man + woman);
		return doubleNameVo;
	}
}
